package com.design.marketPrj.application.shiro;

import com.design.marketPrj.application.bean.PO.User;
import com.design.marketPrj.application.service.UserService;
import com.design.marketPrj.application.util.SpringBeanFactoryUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

public class MyRealm extends AuthorizingRealm {



    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前登录的用户
        User user = (User) principalCollection.getPrimaryPrincipal();
        //通过SimpleAuthenticationInfo做授权
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //添加角色
//        simpleAuthorizationInfo.addRole(user.getRole());
        //添加权限
//        simpleAuthorizationInfo.addStringPermissions(user.getPermissions());
        return simpleAuthorizationInfo;
    }
    /**
     * 认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取用户输入的账号
        String username = (String)authenticationToken.getPrincipal();
        //2.通过username从数据库中查找到user实体
        User user = null;


        //无数据库情况下查询测试
//        user.setUsername("admin");
//        user.setPassword("123456");

        //从数据库中查询

        user = getUserService().getUser(username);

        ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername());



        //3.通过SimpleAuthenticationInfo做身份处理
        AuthenticationInfo  simpleAuthenticationInfo =
                new SimpleAuthenticationInfo(user,user.getPassword(),credentialsSalt,getName());
        //4.用户账号状态验证等其他业务操作
//        if(!user.getAvailable()){
//            throw new AuthenticationException("该账号已经被禁用");
//        }
        //5.返回身份处理对象
        return simpleAuthenticationInfo;
    }

    private UserService getUserService() {
        return SpringBeanFactoryUtils.getBean(UserService.class);
    }

}
